package com.example.crm.controller.api;

import com.example.crm.entity.SalesTeam;
import com.example.crm.entity.TeamMember;
import com.example.crm.service.SalesTeamService;
import com.example.crm.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 销售团队API控制器
 */
@RestController
@RequestMapping("/api/sales/team")
public class SalesTeamAPIController {

    @Autowired
    private SalesTeamService salesTeamService;

    /**
     * 获取团队列表
     */
    @GetMapping("/list")
    public Result<List<SalesTeam>> list(
            @RequestParam(required = false) String search,
            @RequestParam(required = false) String role,
            @RequestParam(required = false) String region) {
        
        try {
            List<SalesTeam> teams = salesTeamService.listTeams();
            
            // 这里实际项目中应该在service层实现过滤
            // 如果没有过滤参数，直接返回所有团队
            if (search == null && role == null && region == null) {
                return Result.success(teams);
            }
            
            // 模拟过滤结果
            List<SalesTeam> filteredTeams = new ArrayList<>();
            for (SalesTeam team : teams) {
                boolean matches = true;
                
                // 名称搜索
                if (search != null && !team.getName().toLowerCase().contains(search.toLowerCase())) {
                    matches = false;
                }
                
                // 区域过滤（实际项目中根据数据结构调整）
                if (region != null && team.getRegionId() != null && 
                    !team.getRegionId().toString().equals(region)) {
                    matches = false;
                }
                
                if (matches) {
                    filteredTeams.add(team);
                }
            }
            
            return Result.success(filteredTeams);
        } catch (Exception e) {
            return Result.error("获取团队列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取团队详情
     */
    @GetMapping("/{id}")
    public Result<SalesTeam> getById(@PathVariable Long id) {
        try {
            SalesTeam team = salesTeamService.getTeamDetail(id);
            if (team == null) {
                return Result.error("团队不存在");
            }
            return Result.success(team);
        } catch (Exception e) {
            return Result.error("获取团队详情失败: " + e.getMessage());
        }
    }

    /**
     * 获取团队成员
     */
    @GetMapping("/member/{id}")
    public Result<TeamMember> getMemberById(@PathVariable Long id) {
        try {
            // 在实际项目中，应添加方法来获取单个成员
            // 这里为了演示，生成模拟数据
            TeamMember member = new TeamMember();
            member.setId(id);
            member.setUserId(10L);
            member.setTeamId(1L);
            member.setRole("member");
            
            // 传递附加信息（在真实项目中应从用户服务获取）
            Map<String, Object> extra = new HashMap<>();
            extra.put("name", "测试用户");
            extra.put("email", "test@example.com");
            extra.put("phone", "13800138000");
            member.setExtra(extra);
            
            return Result.success(member);
        } catch (Exception e) {
            return Result.error("获取成员详情失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有团队成员
     */
    @GetMapping("/members")
    public Result<List<Map<String, Object>>> getAllMembers() {
        try {
            // 生成模拟团队成员数据
            List<Map<String, Object>> members = new ArrayList<>();
            
            Map<String, Object> member1 = new HashMap<>();
            member1.put("id", 101);
            member1.put("name", "张三");
            member1.put("role", "leader");
            member1.put("email", "zhangsan@example.com");
            member1.put("phone", "13800138001");
            members.add(member1);
            
            Map<String, Object> member2 = new HashMap<>();
            member2.put("id", 102);
            member2.put("name", "李四");
            member2.put("role", "manager");
            member2.put("email", "lisi@example.com");
            member2.put("phone", "13800138002");
            members.add(member2);
            
            Map<String, Object> member3 = new HashMap<>();
            member3.put("id", 103);
            member3.put("name", "王五");
            member3.put("role", "member");
            member3.put("email", "wangwu@example.com");
            member3.put("phone", "13800138003");
            members.add(member3);
            
            Map<String, Object> member4 = new HashMap<>();
            member4.put("id", 104);
            member4.put("name", "赵六");
            member4.put("role", "leader");
            member4.put("email", "zhaoliu@example.com");
            member4.put("phone", "13800138004");
            members.add(member4);
            
            Map<String, Object> member5 = new HashMap<>();
            member5.put("id", 105);
            member5.put("name", "钱七");
            member5.put("role", "member");
            member5.put("email", "qianqi@example.com");
            member5.put("phone", "13800138005");
            members.add(member5);
            
            return Result.success(members);
        } catch (Exception e) {
            return Result.error("获取团队成员列表失败: " + e.getMessage());
        }
    }

    /**
     * 添加团队
     */
    @PostMapping
    public Result<Boolean> save(@RequestBody Map<String, Object> params) {
        try {
            SalesTeam team = new SalesTeam();
            team.setName((String) params.get("name"));
            team.setDescription((String) params.get("description"));
            
            // 设置区域ID
            if (params.containsKey("regionId")) {
                team.setRegionId(Long.valueOf(params.get("regionId").toString()));
            }
            
            // 设置团队负责人
            if (params.containsKey("leaderId")) {
                team.setLeaderId(Long.valueOf(params.get("leaderId").toString()));
            }
            
            // 解析成员列表（如果有）
            List<TeamMember> members = new ArrayList<>();
            if (params.containsKey("members")) {
                List<Map<String, Object>> memberList = (List<Map<String, Object>>) params.get("members");
                for (Map<String, Object> memberData : memberList) {
                    TeamMember member = new TeamMember();
                    member.setUserId(Long.valueOf(memberData.get("userId").toString()));
                    member.setRole((String) memberData.get("role"));
                    members.add(member);
                }
            }
            
            boolean success = salesTeamService.addTeam(team, members);
            return Result.success(success);
        } catch (Exception e) {
            return Result.error("添加团队失败: " + e.getMessage());
        }
    }

    /**
     * 更新团队
     */
    @PutMapping("/update")
    public Result<Boolean> update(@RequestBody Map<String, Object> params) {
        try {
            Long id = Long.valueOf(params.get("id").toString());
            SalesTeam team = new SalesTeam();
            team.setId(id);
            team.setName((String) params.get("name"));
            team.setDescription((String) params.get("description"));
            
            // 设置区域ID
            if (params.containsKey("regionId")) {
                team.setRegionId(Long.valueOf(params.get("regionId").toString()));
            }
            
            // 设置团队负责人
            if (params.containsKey("leaderId")) {
                team.setLeaderId(Long.valueOf(params.get("leaderId").toString()));
            }
            
            boolean success = salesTeamService.updateTeam(team);
            return Result.success(success);
        } catch (Exception e) {
            return Result.error("更新团队失败: " + e.getMessage());
        }
    }

    /**
     * 删除团队
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable Long id) {
        try {
            boolean success = salesTeamService.removeById(id);
            return Result.success(success);
        } catch (Exception e) {
            return Result.error("删除团队失败: " + e.getMessage());
        }
    }

    /**
     * 添加团队成员
     */
    @PostMapping("/add")
    public Result<Boolean> addMember(@RequestBody Map<String, Object> params) {
        try {
            Long teamId = Long.valueOf(params.get("teamId").toString());
            String role = (String) params.get("role");
            
            List<Long> userIds = new ArrayList<>();
            if (params.containsKey("userId")) {
                userIds.add(Long.valueOf(params.get("userId").toString()));
            } else if (params.containsKey("userIds")) {
                List<String> userIdStrings = (List<String>) params.get("userIds");
                for (String userId : userIdStrings) {
                    userIds.add(Long.valueOf(userId));
                }
            }
            
            boolean success = salesTeamService.addTeamMembers(teamId, userIds, role);
            return Result.success(success);
        } catch (Exception e) {
            return Result.error("添加团队成员失败: " + e.getMessage());
        }
    }

    /**
     * 删除团队成员
     */
    @DeleteMapping("/delete/{id}")
    public Result<Boolean> deleteMember(@PathVariable Long id) {
        try {
            // 在真实项目中，需要实现删除团队成员的方法
            // 这里模拟成功
            return Result.success(true);
        } catch (Exception e) {
            return Result.error("删除团队成员失败: " + e.getMessage());
        }
    }
} 